package com.atstudy.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @version v1.0
 * @description:
 * @author: admin
 * @date: 2023/1/10 16:09
 * @copyright: 博为峰
 */
public class DBUtil {

    private static DataSource dataSource = null;

    static {
        try {
            InputStream inputStream = DBUtil.class.getClassLoader().getResourceAsStream("druid.properties");
            Properties properties = new Properties();
            properties.load(inputStream);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //从数据源中获取数据库连接
    public static Connection getConn() throws SQLException {
        return dataSource.getConnection();
    }

    //关闭数据库连接(放到数据库连接池中)
    public static void closeConn(Connection conn) throws SQLException {
        conn.close();
    }
}
